var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var bodyParser = require('body-parser');
var poolModule = require('generic-pool');

var passport = require('passport');
var GoogleStrategy = require('passport-google').Strategy;
passport.use(new GoogleStrategy({
        returnURL: 'http://127.0.0.1:3000/authed',
        realm: 'http://127.0.0.1:3000/',
        profile: true
    },
    function(identifier, profile, done) {
        done(null, { auth: true, name: profile.displayName, key: identifier });
    }
));
passport.serializeUser(function(user, done) {
    done(null, { auth: true, name: user.name, key: user.key });
});
passport.deserializeUser(function(id, done) {
    done(null, id.name);
});
exports.passport = passport;

var index = require('./routes/index');
var periodicals = require('./routes/periodicals');
var persons = require('./routes/persons');
var issues = require('./routes/issues');
var articles = require('./routes/articles');
var participations = require('./routes/participation');
var roles = require('./routes/roles');
var search = require('./routes/search');
var timer = require('./routes/timer');

var config = require('./config');

var pool = poolModule.Pool({
        name     : 'oracle',
        create   : function(callback) {
                var config = require('./config');
                var jdbc = require('./lib/jdbc').getJDBCConn();

                var config = {
                    libpath: __dirname + config.jdbc_jar_path,
                    drivername: config.jdbc_drivername,
                    url: config.jdbc_url
                };

                jdbc.initialize(config, function(err, res) {
                    if (err) {
                        console.log(err);
                        callback(err, null);
                    } else {
                        jdbc.open(function(err, conn) {
                            if(err) {
                                console.log(err);
                            }
                            callback(err, jdbc);
                        });
                    }
                });
        },
        destroy  : function(conn) { 
            conn.close(function(err) {
                if(err) {
                    console.log(err);
                }
            }); 
        },
        max      : config.pool_size_max,
        min      : config.pool_size_min, 
        idleTimeoutMillis : config.pool_expiration_time,
        log: config.pool_log
});

process.on( 'SIGINT', function() {
  console.log( "\nGracefully shutting down from SIGINT (Ctrl-C)" );
  pool.destroyAllNow();
  process.exit( );
});

var app = express();

app.use(function(req, res, next){
    req.pool = pool;
    req.model = {};
    req.model.successAlerts = [];
    req.model.infoAlerts = [];
    req.model.warningAlerts = [];
    req.model.dangerAlerts = [];
    req.model.auth = {};
    req.model.auth.bool = false;
    req.model.auth.name = 'anonymous';
    next();
});

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// Initialize express framework
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(session({ secret: 'zpapppxxllerjam,.0.dfa654163210123'})); // It could be not very good! Maybe we should use our own sessionStore
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/Periodicals/', periodicals);
app.use('/Persons/', persons);
app.use('/Issues/', issues);
app.use('/Articles/', articles);
app.use('/Participations/', participations);
app.use('/Roles/', roles);
app.use('/Search/', search);
app.use('/Timer/', timer);


app.use(function(req, res, next) {
        var err = new Error('Not Found');
        err.status = 404;
        next(err);
});

if (app.get('env') === 'development') {
        app.use(function(err, req, res, next) {
                res.status(err.status || 500);
                res.render('error', {
                        message: err.message,
                        error: err
                });
        });
}

app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        req.model.message = err.message;
        req.model.error = {};
        res.render('error', req.model);
});

module.exports = app;